package com.yulang.security.strategy;

import com.yulang.security.result.Result;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.session.InvalidSessionStrategy;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义session失效处理器
 */
public class CustonInvialSessionStrategy implements InvalidSessionStrategy {

    private SessionRegistry sessionRegistry;


    public CustonInvialSessionStrategy(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 要将浏览器中的JESSIONID删除掉
        sessionRegistry.removeSessionInformation(request.getRequestedSessionId());
        cancelCookie(request,response);
        response.getWriter().write(Result.error("SESSION已失效").toJsonString());
        response.getWriter().flush();
    }

    protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("JSESSIONID", (String)null);
        cookie.setMaxAge(0);
        cookie.setPath(this.getCookiePath(request));
        response.addCookie(cookie);
    }

    private String getCookiePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    }



}
